package com.example.administrator.jim.view.main;

import android.content.Context;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.View;
import android.widget.LinearLayout;

import com.example.administrator.jim.R;
import com.example.administrator.jim.view.main.adapter.MessageAdapter;

import java.util.List;

import cn.jpush.im.android.api.JMessageClient;
import cn.jpush.im.android.api.model.Conversation;

/**
 * Created by Administrator on 2018/2/1 0001.
 * Date 2018/2/1 0001
 */

public class MessageView extends LinearLayout {
    private Context mContext;
    private View mMView;
    private RecyclerView mRecyclerView;
    private MessageAdapter mMessageAdapter;
    private List<Conversation> mConversationList;
    private LinearLayoutManager mLinearLayoutManager;

    public MessageView(Context context) {
        this(context,null);
    }

    public MessageView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs,0);
    }

    public MessageView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mContext=context;
        mMView =View.inflate(mContext,R.layout.messageview_layout,this);
        initView();
    }
    private void initListener() {
        mMessageAdapter.setOnDelListener(new MessageAdapter.onSwipeListener() {
            @Override
            public void onDel(int pos) {
                if (pos >= 0 && pos < mConversationList.size()) {
                    mConversationList.remove(pos);
                    mMessageAdapter.notifyItemRemoved(pos);//推荐用这个
                    //如果删除时，不使用mAdapter.notifyItemRemoved(pos)，则删除没有动画效果，
                    //且如果想让侧滑菜单同时关闭，需要同时调用 ((SwipeMenuLayout) holder.itemView).quickClose();
                    //mAdapter.notifyDataSetChanged();
                }
            }
        });
    }

    private void initView() {
        mRecyclerView= (RecyclerView) mMView.findViewById(R.id.view_message_recycle);
        mLinearLayoutManager = new LinearLayoutManager(mContext);
        mRecyclerView.setLayoutManager(mLinearLayoutManager);
    }
    public void initMessageList() {
        mConversationList = JMessageClient.getConversationList();
        if(mConversationList !=null&& mConversationList.size()>0){
            if(mMessageAdapter==null){
                mMessageAdapter = new MessageAdapter(mContext, mConversationList);
                initListener();
                mRecyclerView.setAdapter(mMessageAdapter);
            }else {
                mMessageAdapter.setConversationList(mConversationList);
                mMessageAdapter.notifyDataSetChanged();
            }
        }
    }
}
